﻿using lsw_VoteSys.Models.Database;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace lsw_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class VoteController : ControllerBase
    {
        private readonly lsw_VoteSysContext _db;

        public VoteController(lsw_VoteSysContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 用户投票
        /// </summary>
        /// <param name="projectId">投票项目的ID</param>
        /// <returns>投票结果</returns>
        [HttpPost]
        [Authorize]
        public IActionResult Vote(int projectId)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            var hasVoted = _db.Votes.Any(v => v.ProjectId == projectId && v.UserId == userId);

            if (hasVoted)
            {
                return BadRequest("您已经对该项目投票过");
            }

            var votesCount = _db.Votes.Count(v => v.UserId == userId && v.VoteDate.Date == DateTime.UtcNow.Date);
            if (votesCount >= 5) // 假设每天最多投票5次
            {
                return BadRequest("您今天的投票次数已达到上限");
            }

            var vote = new Vote
            {
                ProjectId = projectId,
                UserId = userId,
                VoteDate = DateTime.UtcNow
            };
            var saveResult = _db.SaveChanges();

            if (saveResult > 0)
            {
                // 更新项目投票数
                var project = _db.Projects.Find(projectId);
                project.VoteCount++;
                _db.SaveChanges();

                return Ok("投票成功");
            }

            return StatusCode(500, "投票失败，请稍后再试");
        }
    }

    public class Vote
    {
        public int Id { get; set; }
        public int ProjectId { get; set; }
        public string UserId { get; set; }
        public DateTime VoteDate { get; set; }
    }

    public class project
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int VoteCount { get; set; }
        // 其他项目字段...
    }
}
